package com.lbjhan.rpc.serializer;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.lbjhan.rpc.pojo.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class KryoSerializer<T> implements ISerializer {
    @Override
    public byte[] serialize(Object obj){
        Kryo kryo = new Kryo();
        kryo.setReferences(true);
        kryo.setRegistrationRequired(false);
        kryo.register(obj.getClass());
        Output output = new Output(new ByteArrayOutputStream());
        kryo.writeObjectOrNull(output, obj, obj.getClass());
        byte[] bytes = output.toBytes();
        return bytes;
    }

    @Override
    public T deserialize(byte[] bytes, Class clazz){
        Kryo kryo = new Kryo();
        kryo.setReferences(true);
        kryo.setRegistrationRequired(false);
        kryo.register(clazz);
        Input input = new Input(new ByteArrayInputStream(bytes));
        T t = (T)kryo.readObject(input, clazz);
        return t;
    }

    public static void main(String[] args) {
        KryoSerializer<User> userKryoSerializer = new KryoSerializer<>();
        byte[] bytes = userKryoSerializer.serialize(new User(1, "tom"));
        System.out.println(bytes.length);
        User user = userKryoSerializer.deserialize(bytes, User.class);
        System.out.println(user);
        /**
         * 6
         * User(id=1, name=tom)
         */
    }
}
